﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Net.Mail;

namespace DatabaseBackup.Library
{
    public static class ErrorHandler
    {

        public static void AddToErrorLog(Exception ex, BackupType type)
        {
            string locationFile = Helpers.ErrorLogLocation + string.Format("ErrorLog-{0:yyyyMMddHHmm}", DateTime.UtcNow) + ".xml";

            XElement doc =
                new XElement("ErrorLog");

            XElement errorLine =
                new XElement("ErrorLine",
                    new XAttribute("ExceptionMessage", ex.Message),
                    new XAttribute("InnerException", ex.InnerException != null ? ex.InnerException.Message : string.Empty),
                    new XAttribute("StackTrace", ex.StackTrace),
                    new XAttribute("Action", type.ToString()));

            doc.Add(errorLine);

            doc.Save(locationFile);

            SendEmail(doc);

        }

        public static void AddToErrorLog(Exception ex)
        {
            string locationFile = Helpers.ErrorLogLocation + string.Format("ErrorLog-{0:yyyyMMddHHmm}", DateTime.UtcNow) + ".xml";

            XElement doc =
                new XElement("ErrorLog");

            XElement errorLine =
                new XElement("ErrorLine",
                    new XAttribute("ExceptionMessage", ex.Message),
                    new XAttribute("InnerException", ex.InnerException != null ? ex.InnerException.Message : string.Empty),
                    new XAttribute("Action", "FTP Transfer"));

            doc.Add(errorLine);

            doc.Save(locationFile);

            SendEmail(doc);

        }

        private static void SendEmail(XElement contents)
        {
            SmtpClient emailClient = new SmtpClient();
            MailMessage message = new MailMessage();

            message.Subject = "Database Backup Error";
            message.To.Add(new MailAddress(Helpers.ErrorLogEmail));
            message.From = new MailAddress(Helpers.ErrorLogEmail, "Database Backup Manager");
            message.Body = contents.ToString();

            emailClient.Send(message);
        }
    }
}
